package com.ecology.str;

import com.sun.deploy.util.StringUtils;

/**
 * 给定两个字符串，判断目标字符串是否存在于源字符串中
 * 并返回下标，反之返回-1
 */
public class FindChildStr {
    public static int findIndexOfChildStr(String source, String target) {
//        return withWhile(source, target);
        return withSkip(source, target);
    }

    private static int withSkip(String source, String target) {
        if (null == source || source.length() < 1) {
            return -1;
        }
        if (null == target || target.length() < 1) {
            return -1;
        }
        int sourceLen = source.length();
        int targetLen = target.length();
        if (targetLen > sourceLen) {
            return -1;
        }
        int result = -1;

        return result;
    }

    private static int withWhile(String source, String target) {
        if (null == source || source.length() < 1) {
            return -1;
        }
        if (null == target || target.length() < 1) {
            return -1;
        }
        int sourceLen = source.length();
        int targetLen = target.length();
        if (targetLen > sourceLen) {
            return -1;
        }
        int result = -1;
        int moved = 0;
        int sourceIndex = 0;
        int targetIndex = 0;
        while (true) {
            String sChar = source.substring(sourceIndex + moved, sourceIndex + moved + 1);
            String tChar = target.substring(targetIndex, targetIndex + 1);
            boolean eq = sChar.equals(tChar);
            if (eq) {
                ++targetIndex;
                ++sourceIndex;
            } else {
                ++moved;
                targetIndex = 0;
                sourceIndex = 0;
            }
            if (eq && targetIndex >= targetLen) {
                result = moved;
                break;
            }
            if (sourceIndex + moved > sourceLen - 1) {
                break;
            }
        }

        return result;
    }

}
